/**
 * 
 */
package org.pump.client.type;

import java.io.UnsupportedEncodingException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.pump.client.codec.Packet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liudong03
 *
 */
public class NullTerminatedString {
	private static final Logger mylog = LoggerFactory.getLogger(NullTerminatedString.class);
	public String charset;
	public String chardata;
	public byte[] bytedata;
	public int len;
	/**
	 * 
	 */
	public NullTerminatedString()
	{
		
	}
	public NullTerminatedString(String data,String charset)
	{
		this.chardata = data;
		this.charset = charset;
		try {
			this.bytedata = this.chardata.getBytes(this.charset);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			mylog.error("can't encode null terminated string",e);
		}
		this.len = this.bytedata.length + 1;
	}
	public static NullTerminatedString readBuffer(IoBuffer in,String charset)
	{
		if(in.remaining() < 1)
		{
			return null;
		}
		NullTerminatedString str = new NullTerminatedString();
		str.charset = charset;
		try {
			str.chardata = in.getString(Charset.forName(str.charset).newDecoder());
		} catch (CharacterCodingException e) {
			// TODO Auto-generated catch block
			mylog.error("can't decode null terminated String",e);
			return null;
		}
		str.len = str.chardata.length() + 1;
		return str;
	}
	
	public boolean writeBuffer(IoBuffer out)
	{		
		if(this.chardata != null && this.chardata.length() > 0)
		{
			out.put(this.bytedata);
			out.put((byte)0x00);
		}
		return true;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "'" + this.chardata + "'";
	}
	
	public int getSize()
	{
		try {
			return this.chardata.getBytes(this.charset).length + 1;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			mylog.error("null terminated string get size fail");
			return -1;
		}
	}
	/**
	 * @return the chardata
	 */
	public String getChardata() {
		return chardata;
	}
	
	

}
